const User = require('../models/user')
const { secret } = require('../config/config')
const jwt = require('jsonwebtoken')
const bcrypCtjs = require('bcryptjs')

module.exports = async function login (req, res, next) {
  const user = await User.findOne({
    username: req.body.username
  })

  if (!user) {
    return res.status(422).send({
      message: '用户名不存在！'
    })
  }

  const isPasswordValid = bcrypCtjs.compareSync(
    req.body.password,
    user.password
  )

  if (!isPasswordValid) {
    return res.status(422).send({
      message: '密码错误！'
    })
  }

  const token = jwt.sign({
    id: String(user._id)
  }, secret)

  res.send({
    token
  })
}
